import 'dart:async';

///
/// 通话中的对话组件
///

import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:qgchat/common/class/eventBus/index.dart';
import 'package:qgchat/common/global/global.dart';
import 'package:qgchat/page/live/videoPage/live/BloC/dialogueBloC/index.dart';
import 'package:qgchat/page/live/videoPage/live/model/videoText.dart';

class LiveDialogue extends StatefulWidget {
  LiveDialogue({Key key}) : super(key: key);

  @override
  _LiveDialogueState createState() => _LiveDialogueState();
}

class _LiveDialogueState extends State<LiveDialogue> {
  ScrollController c = ScrollController();

  @override
  void initState() { 
    super.initState();
    bus.on('listenVideoMessage', (data) {
      VideoTextModel text = VideoTextModel.fromJson(data);
      BlocProvider.of<DialogueBloc>(context).add(AddDialogue(text));
    });
  }

  @override
  void dispose() { 
    bus.off("listenVideoMessage");
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<DialogueBloc, DialogueState>(
      builder: (context, state) {
        // 加载中
        if (state is DialogueLoading) {
          return Container();
        }
        // 加载完
        else if (state is DialogueLoaded) {
          DialogueLoaded currentState = state;
          List<VideoTextModel> list = currentState.list;
          Timer(Duration(milliseconds: 50), () => c.jumpTo(c.position.minScrollExtent));
          return Container(
            width: px(500),
            height: px(200),
            child: ListView.builder(
              controller: c,
              reverse: true,
              itemCount: list.length,
              itemBuilder: (context, i) {
                return Container(
                  child: RichText(
                    text: TextSpan(
                      style: TextStyle(
                        color: col("ffbf40"),
                        fontSize: px(28),
                      ),
                      children: <TextSpan>[
                        TextSpan(text: "${list[i].name}："),
                        TextSpan(text: "${list[i].msg}"),
                      ],
                    ),
                  ),
                );
              },
            ),
          );
        }
        // 加载失败
        else {
          return Container();
        }
      },
    );
  }
}
